package top.rainbowecho.ai.infrastructure.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import top.rainbowecho.ai.domain.model.robot.IAiRobot;
import top.rainbowecho.common.domain.shared.vo.SensitiveRecognizeResult;

import java.io.IOException;

/**
 * @author rainbow
 * @since 2019/11/30 14:24
 */
@Component
@Slf4j
@PropertySource("classpath:bootstrap.yml")
public class AiMqListener {
    private IAiRobot aiRobot;

    @Autowired
    public void setAiRobot(IAiRobot aiRobot) {
        this.aiRobot = aiRobot;
    }

    @RabbitListener(queues = "${blog.mq.routes.fileToAi.routing}")
    public SensitiveRecognizeResult listenFromAi(String imageCode, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        try {
            SensitiveRecognizeResult sensitiveRecognizeResult = aiRobot.sensitiveImageCheck(imageCode);
            channel.basicAck(deliveryTag, false);
            return sensitiveRecognizeResult;
        } catch (Exception e) {
            log.error(e.getMessage());
            // 将消息重新放回队列，并返回一个空label
            channel.basicNack(deliveryTag, false, true);
            return new SensitiveRecognizeResult(false, StringUtils.EMPTY);
        }
    }
}
